﻿namespace EnergyGeneratorSimVisualizer.Serialization
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;
using System.Globalization;

    public static class XElementReaderHelpers
    {
        private static NumberStyles ulongStyle;
        private static NumberStyles intStyle;
        private static NumberStyles doubleStyle;

        static XElementReaderHelpers()
        {
            ulongStyle = NumberStyles.HexNumber;
            intStyle = NumberStyles.HexNumber;
            doubleStyle = NumberStyles.Float;
        }

        public static ulong ReadULongElement(this XElement element, XName elementName)
        {
            string value = ReadElementValue(element, elementName);

            ulong convertedValue;
            if (!ulong.TryParse(value, ulongStyle, null, out convertedValue))
            {
                throw new FormatException("Cannot convert value " + value + " to an ulong!");
            }

            return convertedValue;
        }

        public static int ReadIntegerElement(this XElement element, XName elementName)
        {
            string value = ReadElementValue(element, elementName);

            int convertedValue;
            if (!int.TryParse(value, intStyle, null, out convertedValue))
            {
                throw new FormatException("Cannot convert value " + value + " to an ulong!");
            }

            return convertedValue;
        }

        public static double ReadDoubleElement(this XElement element, XName elementName)
        {
            string value = ReadElementValue(element, elementName);

            double convertedValue;
            if (!double.TryParse(value, doubleStyle, null, out convertedValue))
            {
                throw new FormatException("Cannot convert value " + value + " to an ulong!");
            }

            return convertedValue;
        }

        private static string ReadElementValue(XElement element, XName elementName)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            if (elementName == null)
            {
                throw new ArgumentNullException("elementName");
            }

            var valueElement = element.Element(elementName);

            if (valueElement == null)
            {
                throw new ArgumentException("Element not found: " + elementName);
            }

            return  valueElement.Value;;
        }
    }
}
